import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/singleton_manager.dart';

import '../entity/order_list_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';
import '../views/default_views.dart';
import '../views/dialog_manager.dart';
import 'package:crypto/crypto.dart';

class OrderListPage extends StatefulWidget {
  String orderType;

  OrderListPage({Key? key, this.orderType = ""}) : super(key: key);

  @override
  State<OrderListPage> createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage> {
  List<OrderListData> datas = [];
  var page = 1;
  var payPwd = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getOrderList();
  }

  bool isShowPayBtn(String status) {
    if (status == '5') {
      return true;
    } else {
      return false;
    }
  }

  bool isShowTixingBtn(String status) {
    if (status == '15') {
      return true;
    } else {
      return false;
    }
  }

  bool isShowCancelBtn(String status) {
    if (status == '5') {
      return true;
    } else {
      return false;
    }
  }

  bool isShowReceiptBtn(String status) {
    if (status == '20') {
      return true;
    } else {
      return false;
    }
  }

  bool isShowComment(String status) {
    if (status == '25') {
      return true;
    } else {
      return false;
    }
  }

  bool isShowLogistics(String status) {
    if (status == '20' || status == '25' || status == '30') {
      return true;
    } else {
      return false;
    }
  }

  getOrderList() async {
    dynamic result =
        await Api.orderList({'page': page.toString(), 'size': '20', 'status': widget.orderType});
    OrderListEntity entity = OrderListEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  orderSendNotice(String orderNo) async {
    dynamic result = await Api.orderSendNotice(orderNo);
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("已提醒卖家发货，请耐心等待");
      page = 1;
      getOrderList();
    }
  }

  checkExpress(String orderNo) async {
    dynamic result = await Api.expressMap(orderNo);
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      Routes.navigateTo(context, Routes.orderQueryExpress, params: {'orderNo': orderNo});
    }
  }

  orderReceipt(String orderNo) async {
    var content = const Utf8Encoder().convert(payPwd);
    String md5pwd = "${md5.convert(content)}";

    dynamic result = await Api.orderReceipt({'order_no': orderNo, 'pay_pwd': md5pwd});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("收货成功");
      page = 1;
      getOrderList();
    }
  }

  checkPayPwd() async {
    dynamic result = await Api.checkSetPayPwd();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String pay_pwd_exists = jsonResult['data']['pay_pwd_exists'];
      return pay_pwd_exists;
    }
    return "0";
  }

  _showDialogForPinInput(context, orderNo) {
    payPwd = '';
    AwesomeDialog(
      context: context,
      animType: AnimType.SCALE,
      dialogType: DialogType.NO_HEADER,
      body: Container(
        padding: EdgeInsets.only(top: 5.w, left: 20.w, right: 20.w),
        child: Column(
          children: [
            Text(
              "请输入支付密码",
              style: TextStyle(color: Config.colorText1, fontSize: 30.sp),
            ),
            Padding(
              padding: EdgeInsets.only(top: 30.w),
            ),
            PinCodeTextField(
              appContext: context,
              length: 6,
              obscureText: true,
              // controller: textEditingController,
              onChanged: (value) {},
              keyboardType: TextInputType.phone,
              onCompleted: (value) {
                payPwd = value;
              },
              // pinTheme: PinTheme(
              //   shape: PinCodeFieldShape.box, //输入框的形状
              //   borderRadius: const BorderRadius.all(Radius.circular(10)),
              //   // 其他可以设置可以自己参考，比如有输入文字的时候输入框是什么颜色，不能输入的时候是什么颜色等
              // ),
            ),
            InkWell(
              onTap: () {
                Routes.navigateTo(context, Routes.mineChangePassword,
                    params: {'pageTitle': '修改支付密码'});
              },
              child: Container(
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: 2.w),
                child: Text(
                  "忘记密码?",
                  style: TextStyle(
                      color: Config.colorText1,
                      fontSize: 25.sp,
                      decoration: TextDecoration.underline),
                ),
              ),
            ),
          ],
        ),
      ),
      title: '',
      desc: '',
      btnOkText: '确定',
      btnOkColor: Config.colorMain,
      btnOkOnPress: () {
        // print('oncompletd $payPwd');
        if (payPwd.isEmpty) {
          return;
        }
        orderReceipt(orderNo);
      },
    ).show();
  }

  orderCancel(String orderNo, int index) async {
    dynamic result = await Api.cancelOrder('$orderNo/$index');
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("订单取消成功");
      page = 1;
      getOrderList();
    }
  }

  cancelOrder(BuildContext context, String orderNo) async {
    Picker(
        adapter: PickerDataAdapter(
            pickerData: SingletonManager.instance.orderCancelReason, isArray: false),
        height: 350.w,
        headerDecoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.w),
            topRight: Radius.circular(20.w),
          ),
        ),
        itemExtent: 70.w,
        confirmText: '确定',
        cancelText: '取消',
        columnPadding: EdgeInsets.all(15.w),
        onConfirm: (picker, list) {
          // LogUtil.v(SingletonManager.instance.orderCancelReason[list[0]]);
          orderCancel(orderNo, list[0]);
        }).showModal(context, backgroundColor: Colors.transparent);
  }

  bool isPay(String payMoney, String payMoney1) {
    if (payMoney.isNotEmpty && payMoney != '0') {
      return true;
    }
    if (payMoney1.isNotEmpty && payMoney1 != '0') {
      return true;
    }
    return false;
  }

  Widget getOrderItem(int index) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.w, horizontal: 25.w),
      padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
      decoration: BoxDecoration(
        color: (Config.colorWhite),
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              CachedNetworkImage(
                imageUrl: CommonUtils.compressImageUrl(datas[index].store.logo, 50, 50),
                fit: BoxFit.fill,
                width: 32.w,
                height: 32.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: 32.w,
                    height: 32.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
              Padding(
                padding: EdgeInsets.only(left: 10.w),
              ),
              Expanded(
                child: Text(
                  datas[index].store.name,
                  style: TextStyle(fontSize: 24.sp),
                ),
              ),
              Text(
                datas[index].statusStr,
                style: TextStyle(fontSize: 22.sp, color: Colors.red),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.w),
          ),
          // Container(
          //   height: 120.w * datas[index].orderGoods.length,
          //   width: double.infinity,
          //   child: ListView.builder(
          //     scrollDirection: Axis.vertical,
          //     padding: EdgeInsets.symmetric(vertical: 1.w),
          //     itemCount: datas[index].orderGoods.length,
          //     physics: const NeverScrollableScrollPhysics(),
          //     itemBuilder: (BuildContext context, int index2) {
          //       return getProductItem(index, datas[index].orderGoods[index2]);
          //     },
          //   ),
          // ),
          SizedBox(
            height: 120.w * datas[index].orderGoods.length,
            width: double.infinity,
            child: Column(
              children: List<Widget>.generate(datas[index].orderGoods.length,
                  (index2) => getProductItem(index, datas[index].orderGoods[index2])),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.w),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Text(
                "共${datas[index].goodsCount}件商品",
                style: TextStyle(fontSize: 22.sp, color: Config.colorText1),
              ),
              Padding(
                padding: EdgeInsets.only(left: 10.w),
              ),
              Text(
                "合计:",
                style: TextStyle(fontSize: 22.sp, color: Config.colorText1),
              ),
              Text(
                isPay(datas[index].payMoney, datas[index].payMoney1)
                    ? CommonUtils.formatAmountUnit(datas[index].payMoney, datas[index].payCompany,
                        datas[index].payMoney1, datas[index].payCompany1)
                    : CommonUtils.formatAmountUnit(datas[index].money, datas[index].company,
                        datas[index].money1, datas[index].company1),
                style: TextStyle(fontSize: 22.sp, color: Colors.red),
              ),
            ],
          ),
          Divider(
            color: Config.colorDivider,
            height: 38.w,
            thickness: 2.w,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Visibility(
                visible: isShowCancelBtn(datas[index].status),
                child: Container(
                  margin: EdgeInsets.only(left: 15.w),
                  width: 140.w,
                  height: 46.w,
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {cancelOrder(context, datas[index].orderNo)},
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        BorderSide(color: Config.colorText3, width: 2.w),
                      ),
                    ),
                    child: Text(
                      '取消订单',
                      style: TextStyle(fontSize: 18.sp, color: Config.colorText3),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible:
                    isShowTixingBtn(datas[index].status) && datas[index].isShowNoticeSend == '1',
                child: Container(
                  margin: EdgeInsets.only(left: 15.w),
                  width: 140.w,
                  height: 46.w,
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {orderSendNotice(datas[index].orderNo)},
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        BorderSide(color: Config.colorText3, width: 2.w),
                      ),
                    ),
                    child: Text(
                      '提醒发货',
                      style: TextStyle(fontSize: 18.sp, color: Config.colorText3),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible: isShowPayBtn(datas[index].status),
                child: Container(
                  margin: EdgeInsets.only(left: 15.w),
                  width: 120.w,
                  height: 46.w,
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {
                      Routes.navigateTo(context, Routes.orderCashier, params: {
                        'amount': CommonUtils.formatAmountUnit(datas[index].money,
                            datas[index].company, datas[index].money1, datas[index].company1),
                        'orderNo': datas[index].orderNo,
                        'payApiType': datas[index].tag,
                        'skuId': datas[index].orderGoods[0].skuSnap.id
                      }).then((value) {
                        page = 1;
                        getOrderList();
                      })
                    },
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        BorderSide(color: Config.colorMain, width: 2.w),
                      ),
                    ),
                    child: Text(
                      '付款',
                      style: TextStyle(fontSize: 18.sp, color: Config.colorMain),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible: isShowComment(datas[index].status),
                child: Container(
                  margin: EdgeInsets.only(left: 15.w),
                  width: 120.w,
                  height: 46.w,
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () {
                      SingletonManager.instance.currentOrderListItem = datas[index];
                      Routes.navigateTo(context, Routes.publishComment, params: {
                        'sourceType': "1",
                      }).then((value) {
                        page = 1;
                        getOrderList();
                      });
                    },
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        BorderSide(color: Config.colorMain, width: 2.w),
                      ),
                    ),
                    child: Text(
                      '评价',
                      style: TextStyle(fontSize: 18.sp, color: Config.colorMain),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible: isShowReceiptBtn(datas[index].status),
                child: Container(
                  margin: EdgeInsets.only(left: 15.w),
                  width: 140.w,
                  height: 46.w,
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () async {
                      String isCheck = await checkPayPwd();
                      if (isCheck == '1') {
                        // DialogManager.showDefaultDialog(
                        //   context,
                        //   "是否确认收货",
                        //   () async {
                        //
                        //   },
                        // );
                        _showDialogForPinInput(context, datas[index].orderNo);
                      } else {
                        //请用户去设置支付密码
                        DialogManager.showDefaultDialog(context, "你还未设置支付密码，请前往设置", () {
                          Routes.navigateTo(context, Routes.mineChangePassword,
                              params: {'pageTitle': '修改支付密码'});
                        });
                      }
                    },
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        BorderSide(color: Config.colorMain, width: 2.w),
                      ),
                    ),
                    child: Text(
                      '确认收货',
                      style: TextStyle(fontSize: 18.sp, color: Config.colorMain),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible: isShowLogistics(datas[index].status),
                child: Container(
                  margin: EdgeInsets.only(left: 15.w),
                  width: 140.w,
                  height: 46.w,
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {checkExpress(datas[index].orderNo)},
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(24.w),
                        ),
                      ),
                      side: MaterialStateProperty.all(
                        BorderSide(color: Config.colorMain, width: 2.w),
                      ),
                    ),
                    child: Text(
                      '查看物流',
                      style: TextStyle(
                        fontSize: 18.sp,
                        color: Config.colorMain,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget getProductItem(int index, OrderListDataOrderGoods item) {
    return Container(
      height: 120.w,
      child: InkWell(
        onTap: () {
          Routes.navigateTo(context, Routes.orderDetail, params: {'orderNo': datas[index].orderNo});
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(right: 20.w),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: CachedNetworkImage(
                  imageUrl: CommonUtils.compressImageUrl(item.skuSnap.imgPath, 150, 150),
                  fit: BoxFit.fill,
                  width: 100.w,
                  height: 100.w,
                  errorWidget: (context, url, error) {
                    return Image.asset(
                      'assets/images/bg_default_400.png',
                      width: 100.w,
                      height: 100.w,
                      fit: BoxFit.fill,
                    );
                  },
                ),
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.only(top: 8.w),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: 420.w,
                      child: Text(
                        item.skuSnap.goods.name,
                        softWrap: false,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                      ),
                    ),
                    Container(
                      alignment: Alignment.centerRight,
                      width: 120.w,
                      child: Text(
                        item.statusDetail,
                        softWrap: false,
                        style: TextStyle(color: Colors.red, fontSize: 22.w),
                      ),
                    ),
                  ],
                ),
                Container(
                  width: 540.w,
                  margin: EdgeInsets.only(top: 5.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        item.skuSnap.specVal.toString(),
                        softWrap: true,
                        style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                      ),
                      Text(
                        "X${item.buyNum}",
                        softWrap: true,
                        style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 12.w),
                ),
                Text(
                  CommonUtils.formatAmountUnit(
                      item.money, item.company, item.money1, item.company1),
                  softWrap: true,
                  style: TextStyle(color: (Config.colorText1), fontSize: 20.w),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return datas.isNotEmpty
        ? Container(
            width: double.infinity,
            height: double.infinity,
            child: EasyRefresh(
              header: const MaterialHeader(),
              footer: const MaterialFooter(),
              onRefresh: () async {
                await Future.delayed(const Duration(milliseconds: 200), () {
                  page = 1;
                  getOrderList();
                });
              },
              onLoad: () async {
                getOrderList();
              },
              child: ListView.builder(
                shrinkWrap: true,
                // scrollDirection: Axis.vertical,
                // physics: const BouncingScrollPhysics(),
                padding: EdgeInsets.symmetric(vertical: 5.w),
                itemCount: datas.length,
                itemBuilder: (BuildContext context, int index) {
                  return getOrderItem(index);
                },
              ),
            ),
          )
        : showNullData();
  }
}
